/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tools;

import graphics.ProgressFrame;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 *
 * @author Mattia
 */
public class Extractor {

    private String zipPath;
    private String zipFile;
    private ProgressFrame rsc;
    private TimeManager time;

    public Extractor(ProgressFrame rsc, String path) {
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            this.zipPath = path.substring(0, path.lastIndexOf("\\") + 1);
        } else {
            this.zipPath = path.substring(0, path.lastIndexOf("/") + 1);
        }
        this.zipFile = path;
        this.rsc = rsc;
        time = new TimeManager(rsc);
        System.out.println("Path: " + zipPath);
        System.out.println("File: " + zipFile);
    }

    public void extract() {
        
        try {
            System.out.println("======================\nCONFIG EXTRACT\n======================");
            System.out.println();
            rsc.ProgressBar.setIndeterminate(true);
            time.start();
            rsc.Action.setText("Apertura di "+zipFile);
            rsc.ProgressBar.setMaximum(new ZipFile(zipFile).size());
            System.out.println("ProgressBar max: "+rsc.ProgressBar.getMaximum());
            byte[] buf = new byte[1024];
            rsc.Action.setText("Apertura del buffer...");
            ZipInputStream zinstream = new ZipInputStream(new FileInputStream(zipFile));
            rsc.ProgressBar.setIndeterminate(false);
            ZipEntry zentry = zinstream.getNextEntry();

            File archive = new File(this.zipPath+""+zentry.getName());
            System.out.println("======================\nPATH: "+archive.getAbsolutePath()+"\n======================");
            
            if(archive.exists()) {
                // già scaricato
                MessageManager.info(rsc, "Hai già estratto questo archivio", "Archivio già estratto");
            } else {
            for (int i=1; zentry != null; i++) {
                rsc.ProgressBar.setValue(i);
                String entryName = zentry.getName();
                rsc.Action.setText("Extract "+entryName+"...");
                //System.out.println("Name of  Zip Entry : " + entryName);
                if (zentry.isDirectory()) {
                    new File(zipPath + entryName).mkdir();
                } else {
                    FileOutputStream outstream = new FileOutputStream(zipPath + entryName);
                    int n;

                    while ((n = zinstream.read(buf, 0, 1024)) > -1) {
                        outstream.write(buf, 0, n);

                    }
                    rsc.Action.setText("Extract "+entryName+"... Fatto!");
                    outstream.close();
                }
                System.out.print("\n - Estratto: "+entryName+".\n\t -> Changing permission: ");
                File tmp = new File(zipPath + entryName);
                System.out.print(tmp.setReadable(true, true)?"r":"-");
                System.out.print(tmp.setWritable(true, true)?"w":"-");
                System.out.print(tmp.setExecutable(true, true)?"x":"-");
                zinstream.closeEntry();
                zentry = zinstream.getNextEntry();
            }
            zinstream.close();
            rsc.BTN_Annulla.setText("Chiudi");
            time.stop();
            }
        } catch (FileNotFoundException ex) {
            MessageManager.error(rsc, ex.getMessage(), "Extract: FileNotFoundException");
            Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            MessageManager.error(rsc, ex.getMessage(), "Extract: IOException");
            Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
